package com.wu.family.utils.img;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.widget.ImageView;


public class LocalBitmapMgr {
	private ExecutorService mService = Executors.newFixedThreadPool(8);
	int maxMemory = (int) Runtime.getRuntime().maxMemory();  
    int cacheSize = maxMemory / 8;
	private LruCache<String, Bitmap> mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {  
        @Override  
        protected int sizeOf(String key, Bitmap bitmap) {  
            return bitmap.getRowBytes() * bitmap.getHeight();  
        }  
    };  
	//private Map<String, WeakReference<Bitmap>> mCache = new HashMap<String, WeakReference<Bitmap>>();
	private static LocalBitmapMgr instance = null;
	public static LocalBitmapMgr getInstance() {
		if (instance == null) {
			instance = new LocalBitmapMgr();
		}
		
		return instance;
	}
	
	public void addBitmap(String key, Bitmap bitmap) {
		 mMemoryCache.put(key, bitmap);
	}
	
	public Bitmap getBitmap(String key) {
		return mMemoryCache.get(key);
	}
	
	public void removeKey(String key) {
		mMemoryCache.remove(key);
	}
	
	public void loadBitmap(ImageView imageView, String httpUrl, SetBitmapCallBack callBack){
		if (callBack == null) {
			callBack = defaultCallBack;
		}
		imageView.setTag(httpUrl);
		mService.submit(new Runnable() {
			
			@Override
			public void run() {
				
			}
		});
	}
	
	Runnable runnable;
	
	interface SetBitmapCallBack{
		public void setBitmap(ImageView imageView, String url, Bitmap bitmap);
	}
	
	SetBitmapCallBack defaultCallBack = new SetBitmapCallBack() {
		
		@Override
		public void setBitmap(ImageView imageView, String url, Bitmap bitmap) {
			if (imageView.getTag() != null && imageView.getTag().equals(url)) {
				imageView.setImageBitmap(bitmap);
			}
		}
	};
	
	public void recycle() {
		HashMap<String, Bitmap> map = (HashMap<String, Bitmap>) mMemoryCache.snapshot();
		for (Map.Entry entry : map.entrySet()) {
			String key = (String)entry.getKey();
			System.out.println("key:" + key);
			Bitmap bitmap = map.get(key);
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
				//System.out.println("bitmap recycle---Local");
			}
			mMemoryCache.remove(key);
		}
		map.clear();
	}

}